package com.uilt;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.net.ResponseCache;


public abstract class BaseController extends HttpServlet {

    public abstract Class getServletClass();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("dddd ");
        String type = req.getParameter("type");
        try {
          Class servletClass = getServletClass();
          Object o = servletClass.newInstance();
          resp.setCharacterEncoding("utf-8");
          //获取具体的方法
          Method method = servletClass.getMethod(type, HttpServletRequest.class, HttpServletResponse.class);
          //执行
          Object invoke = method.invoke(o, req, resp);
          if(invoke instanceof  String){
               String viewName=(String)invoke;
               req.getRequestDispatcher(viewName+".jsp").forward(req,resp);
          }else if(invoke instanceof ResPoneEntity){
              //
              ResPoneEntity resPoneEntity=(ResPoneEntity)invoke;
              //JSON：实现json和java 对象之间的转换
              //转JSon字符串
              String json = JSON.toJSONString(resPoneEntity);
              //写出json到响应对象中
              PrintWriter writer = resp.getWriter();
              writer.write(json);
              writer.flush();
          }
          else if(invoke instanceof LayuiTable){
              //
              LayuiTable layuiTable=(LayuiTable)invoke;
              //JSON：实现json和java 对象之间的转换
              //转JSon字符串
              String json = JSON.toJSONString(layuiTable);
              //写出json到响应对象中
              PrintWriter writer = resp.getWriter();
              writer.write(json);
              writer.flush();
          }
          else if(invoke instanceof InitMenus){
              //
              InitMenus initMenus=(InitMenus)invoke;
              //JSON：实现json和java 对象之间的转换
              //转JSon字符串
              String json = JSON.toJSONString(initMenus);
              //写出json到响应对象中
              PrintWriter writer = resp.getWriter();
              writer.write(json);
              writer.flush();
          }
      }catch (Exception e){
          e.printStackTrace();
      }


    }
}
